from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required
from . import device
from .. import db
from ..models import Device
from datetime import datetime
from sqlalchemy import or_

@device.route('/devices')
@login_required
def device_list():
    # 获取查询参数
    search = request.args.get('search', '')
    device_type = request.args.get('device_type', '')
    status = request.args.get('status', '')
    page = request.args.get('page', 1, type=int)
    per_page = 10

    # 构建查询
    query = Device.query
    
    if search:
        query = query.filter(or_(
            Device.device_id.like(f'%{search}%'),
            Device.name.like(f'%{search}%'),
            Device.location.like(f'%{search}%')
        ))
    
    if device_type:
        query = query.filter(Device.device_type == device_type)
        
    if status:
        query = query.filter(Device.status == status)

    # 排序和分页
    pagination = query.order_by(Device.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False)
    devices = pagination.items

    return render_template('device/list.html',
                         devices=devices,
                         pagination=pagination,
                         search=search,
                         device_type=device_type,
                         status=status,
                         title='设备管理')

@device.route('/devices/add', methods=['GET', 'POST'])
@login_required
def device_add():
    if request.method == 'POST':
        device_id = request.form.get('device_id')
        name = request.form.get('name')
        device_type = request.form.get('device_type')
        location = request.form.get('location')
        description = request.form.get('description')
        
        if Device.query.filter_by(device_id=device_id).first():
            flash('设备ID已存在', 'danger')
            return redirect(url_for('device.device_add'))
        
        device = Device(
            device_id=device_id,
            name=name,
            device_type=device_type,
            location=location,
            description=description
        )
        
        db.session.add(device)
        db.session.commit()
        flash('设备添加成功', 'success')
        return redirect(url_for('device.device_list'))
    
    return render_template('device/add.html', title='添加设备')

@device.route('/devices/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def device_edit(id):
    device = Device.query.get_or_404(id)
    
    if request.method == 'POST':
        device.name = request.form.get('name')
        device.device_type = request.form.get('device_type')
        device.location = request.form.get('location')
        device.description = request.form.get('description')
        device.status = request.form.get('status')
        
        # 如果状态改变，更新最后在线时间
        if device.status == 'online':
            device.last_online = datetime.utcnow()
            
        device.updated_at = datetime.utcnow()
        
        db.session.commit()
        flash('设备更新成功', 'success')
        return redirect(url_for('device.device_list'))
    
    return render_template('device/edit.html', device=device, title='编辑设备')

@device.route('/devices/delete/<int:id>')
@login_required
def device_delete(id):
    device = Device.query.get_or_404(id)
    db.session.delete(device)
    db.session.commit()
    flash('设备删除成功', 'success')
    return redirect(url_for('device.device_list')) 